package edu.cuit.zhuyimeng.uaa.controller;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import edu.cuit.zhuyimeng.framework.common.exception.QueryException;
import edu.cuit.zhuyimeng.framework.common.exception.UpdateException;
import edu.cuit.zhuyimeng.framework.common.result.CodeWrapper;
import edu.cuit.zhuyimeng.framework.common.result.CommonResult;
import edu.cuit.zhuyimeng.framework.common.result.HttpStatusCodeConstants;
import edu.cuit.zhuyimeng.framework.common.util.ServletUtils;
import edu.cuit.zhuyimeng.uaa.exception.AuthenticationException;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@ControllerAdvice
@Slf4j
@RestController
public class GlobalExceptionHandler {

    @GetMapping("/favicon.ico")
    @ResponseBody
    @Operation(hidden = true)
    public void favicon() {

    }

    @ExceptionHandler
    public void handleException(Exception e, HttpServletResponse response) {

        if (e instanceof AuthenticationException exception) {
            CodeWrapper code = exception.getCode();

            ServletUtils.writeCodeJSON(response, CommonResult.error(Objects.requireNonNullElse(code, HttpStatusCodeConstants.FORBIDDEN), exception.getMessage()));

        }  else if (e instanceof NotLoginException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.UNAUTHORIZED, e.getMessage()));
        } else if (e instanceof NotPermissionException exception) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.FORBIDDEN, exception.getMessage()));
        } else if (e instanceof MethodArgumentNotValidException exception) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.BAD_REQUEST,exception.getBindingResult().getAllErrors().get(0).getDefaultMessage()));
        } else if (e instanceof QueryException || e instanceof UpdateException) {
            ServletUtils.writeCodeJSON(response, CommonResult.error(HttpStatusCodeConstants.BAD_REQUEST,e.getMessage()));
        }else  {
            e.printStackTrace();
            ServletUtils.writeCodeJSON(response, CommonResult.error(e.getMessage()));
        }

    }

}
